/*
 * Wiiuse-based input handler
 *
 */
#include "global.h"
#include "InputHandler_Wii.h"
#include "RageUtil.h"
#include "RageLog.h"
#include "RageDisplay.h"
#include <wiiuse/wpad.h>
#include <ogc/pad.h>

InputHandler_Wii::InputHandler_Wii()
{}

InputHandler_Wii::~InputHandler_Wii()
{
	
}

struct state_t {
	bool start, select;
	bool up, down, left, right;
	bool a, b;
};

void InputHandler_Wii::Update(float fDeltaTime)
{
	WPAD_ScanPads();
	PAD_ScanPads();
	
	struct state_t state;
	memset(&state, 0, sizeof(struct state_t));
	
	u32 type;
	for(int i = 0; i < 2; i++) {
		memset(&state, 0, sizeof(struct state_t));
		s32 result = WPAD_Probe(i, &type);
		u32 pressed;
		
		if(result == WPAD_ERR_NONE) {
			pressed = WPAD_ButtonsDown(i) | WPAD_ButtonsHeld(i);
			if(pressed & WPAD_BUTTON_PLUS)
				state.start = true;
			if(pressed & WPAD_BUTTON_MINUS)
				state.select = true;
			if(pressed & WPAD_BUTTON_UP)
				state.up = true;
			if(pressed & WPAD_BUTTON_DOWN)
				state.down = true;
			if(pressed & WPAD_BUTTON_LEFT)
				state.left = true;
			if(pressed & WPAD_BUTTON_RIGHT)
				state.right = true;
			if(pressed & WPAD_BUTTON_A)
				state.a = true;
			if(pressed & WPAD_BUTTON_B)
				state.b = true;
			
			if(pressed & WPAD_BUTTON_HOME)
				exit(0);
		}
		
		pressed = PAD_ButtonsDown(i) | PAD_ButtonsHeld(i);
		if(pressed & PAD_BUTTON_START)
			state.start = true;
		if(pressed & PAD_TRIGGER_Z)
			state.select = true;
		if(pressed & PAD_BUTTON_UP)
			state.up = true;
		if(pressed & PAD_BUTTON_DOWN)
			state.down = true;
		if(pressed & PAD_BUTTON_LEFT)
			state.left = true;
		if(pressed & PAD_BUTTON_RIGHT)
			state.right = true;
		if(pressed & PAD_BUTTON_A)
			state.a = true;
		if(pressed & PAD_BUTTON_B)
			state.b = true;
		
		InputDevice id = InputDevice(DEVICE_JOY1 + i);
		ButtonPressed(DeviceInput(id, JOY_1), state.start);
		ButtonPressed(DeviceInput(id, JOY_2), state.select);
		ButtonPressed(DeviceInput(id, JOY_UP), state.up);
		ButtonPressed(DeviceInput(id, JOY_DOWN), state.down);
		ButtonPressed(DeviceInput(id, JOY_LEFT), state.left);
		ButtonPressed(DeviceInput(id, JOY_RIGHT), state.right);
		ButtonPressed(DeviceInput(id, JOY_3), state.a);
		ButtonPressed(DeviceInput(id, JOY_4), state.b);
	}
	
	InputHandler::UpdateTimer();
}


void InputHandler_Wii::GetDevicesAndDescriptions(vector<InputDevice>& vDevicesOut, vector<CString>& vDescriptionsOut)
{
	vDevicesOut.push_back( DEVICE_JOY1 );
	vDescriptionsOut.push_back( "Wiimote" );
	vDevicesOut.push_back( DEVICE_JOY2 );
	vDescriptionsOut.push_back( "Wiimote" );
}
